package com.qdaily.ui.ui.views;

import android.app.AlertDialog;
import android.content.*;
import com.qdaily.supportlibrary.request.JsonData;
import com.qdaily.supportlibrary.util.NetUtil;
import com.qdaily.supportlibrary.util.QDJsonUtil;
import com.qdaily.supportlibrary.util.QLog;
import com.qdaily.ui.QDBaseActivity;
import com.qdaily.ui.R;
import com.qdaily.ui.data.DataBase.PraiseDAO;
import com.qdaily.ui.data.EventModel.EventCOPChange;
import com.qdaily.ui.data.UserInformationManager;
import com.qdaily.ui.net.NetConfigs;
import com.qdaily.ui.net.QDEnum;
import com.qdaily.ui.net.QdailyNetwork;
import com.qdaily.ui.net.entity.CommentsEntity;
import com.qdaily.ui.net.entity.LikeItEntity;
import com.qdaily.ui.net.entity.SendCommentEntity;
import com.qdaily.ui.net.model.ArticleInfoShare;
import com.qdaily.ui.net.model.CommentMeta;
import com.qdaily.ui.ui.LoginActivity;
import com.qdaily.ui.ui.adapter.CommentsAdapter;
import com.qdaily.ui.util.BusProvider;

/**
 * 评论管理者，里面有2个adapter以及底部toolbar对象
 * <p/>
 * Created with IntelliJ IDEA.
 * User: Felix
 * Date: 4/29/15
 * Time: 17:05
 * QQ:74104
 * Email:lovejiuwei@gmail.com
 */
public class CommentController implements QdailyNetwork.OnRequestCallBackListener,
        CommentsAdapter.IOnCommentItemClick,
        OnRefreshAndLoadMoreListener,
        InputBar.InputBarInterface {

    private CommentsAdapter commentsAdapter;

    private int articleOrPaperId;//id=文章id || 问卷id
    private QDEnum.DetailEnum mDetailEnum = QDEnum.DetailEnum.ARTICLE;
    private QDBaseActivity qdBaseActivity;

    private QdailyNetwork qdailyNetwork;
    private String onClickItems[] = {};
    private AlertDialog.Builder alertDialog;

    private QDCommentView mCommentView; //要监听的滚动View
    private boolean isLoading = false;
    private boolean isCommentEnd = false;
    private long lastCommentTime;

    private InputBar inputBar;
    private ShareDialog shareDialog;

    private OnCommentSuccessListener onCommentSuccessListener;
    private OnPraiseSuccessListener onPraiseSuccessListener;

    private PraiseDAO praiseDAO;

    public CommentController(QDBaseActivity qdBaseActivity,
                             CommentsAdapter commentsAdapter,
                             InputBar inputBar,
                             int articleOrPaperId,
                             QDEnum.DetailEnum mDetailEnum) {
        this.qdBaseActivity = qdBaseActivity;
        this.commentsAdapter = commentsAdapter;
        this.articleOrPaperId = articleOrPaperId;
        this.mDetailEnum = mDetailEnum;
        this.inputBar = inputBar;

        this.qdailyNetwork = new QdailyNetwork(qdBaseActivity, this);
        this.alertDialog = new AlertDialog.Builder(qdBaseActivity);
        this.onClickItems = new String[]{qdBaseActivity.getString(R.string.comment_dialog_1).toString(), qdBaseActivity.getString(R.string.comment_dialog_2).toString(), qdBaseActivity.getString(R.string.comment_dialog_3).toString()};
        if (commentsAdapter != null)
            this.commentsAdapter.setiOnCommentItemClick(this);
        inputBar.setBarInterface(this);
        this.shareDialog = new ShareDialog(qdBaseActivity);
        this.praiseDAO = PraiseDAO.getInstance();
    }

    public void setArticleInfoShare(ArticleInfoShare articleInfoShare) {
        shareDialog.setArticleInfoShare(articleInfoShare);
    }

    public OnCommentSuccessListener getOnCommentSuccessListener() {
        return onCommentSuccessListener;
    }

    public void setOnCommentSuccessListener(OnCommentSuccessListener onCommentSuccessListener) {
        this.onCommentSuccessListener = onCommentSuccessListener;
    }

    public OnPraiseSuccessListener getOnPraiseSuccessListener() {
        return onPraiseSuccessListener;
    }

    public void setOnPraiseSuccessListener(OnPraiseSuccessListener onPraiseSuccessListener) {
        this.onPraiseSuccessListener = onPraiseSuccessListener;
    }

    private void requestPraise(int commentID) {
        if (isLoading) //点赞hold住
            return;
        isLoading = true;

        String praise_type = "";
        int serverId = articleOrPaperId;
        if (commentID > 0) {
            praise_type = QDEnum.COPEnum.COMMENT.value;
            serverId = commentID;
        } else {
            switch (mDetailEnum) {
                case ARTICLE:
                    praise_type = QDEnum.COPEnum.ARTICLE.value;
                    break;
                case VOTE:
                    praise_type = QDEnum.COPEnum.PAPER.value;
                    break;
                case VOTERESULT:
                    praise_type = QDEnum.COPEnum.PAPER.value;
                    break;
                default:
                    praise_type = QDEnum.COPEnum.ARTICLE.value;
                    break;
            }
        }
        boolean isPraise = praiseDAO.isPraise(serverId, praise_type);
        praiseDAO.save(serverId, isPraise ? 2 : 1, praise_type);
        qdailyNetwork.requestLikeIt(praise_type, serverId, isPraise ? 2 : 1);
    }

    private void requestComment(int commentId, String content) {
        String type = QDEnum.COPEnum.ARTICLE.value;
        switch (mDetailEnum) {
            case ARTICLE:
                type = QDEnum.COPEnum.ARTICLE.value;
                break;
            case VOTE:
                type = QDEnum.COPEnum.PAPER.value;
                break;
            case VOTERESULT:
                type = QDEnum.COPEnum.PAPER.value;
                break;
        }
        qdailyNetwork.requestSendComment(type, content, articleOrPaperId, commentId < 0 ? 0 : commentId);
    }

    @Override
    public void onResponse(NetUtil.NetParams params, JsonData response) {
        isLoading = false;
        if (params instanceof NetConfigs.RequestSendComment) //POST评论
        {
            NetConfigs.RequestSendComment requestSendComment = (NetConfigs.RequestSendComment) params;
            SendCommentEntity sendCommentEntity = QDJsonUtil.Json2Object(response.toString(), SendCommentEntity.class);
            if (null != sendCommentEntity && null != sendCommentEntity.getResponse() &&
                    sendCommentEntity.getMeta().getStatus() == NetConfigs.HTTP_RESPONSE_200) {
                if (requestSendComment.getCommentId() == 0) { //文章评论
                    CommentMeta commentMeta = sendCommentEntity.translationParentModel();
                    if (commentsAdapter != null)
                        commentsAdapter.addCommentParentView(commentMeta);
                } else  //子评论
                {
                    if (commentsAdapter != null)
                        commentsAdapter.addCommentChildView(requestSendComment.getCommentId(), sendCommentEntity.translationChildModel());
                }

                int comment_count = sendCommentEntity.getResponse().getComment_count();
                EventCOPChange copChange = new EventCOPChange(mDetailEnum, articleOrPaperId);
                copChange.setCopId(requestSendComment.getCommentId());
                copChange.setCopEnum(requestSendComment.getCommentId() == 0 ? (mDetailEnum == QDEnum.DetailEnum.ARTICLE ? QDEnum.COPEnum.ARTICLE : QDEnum.COPEnum.PAPER) : QDEnum.COPEnum.COMMENT);
                copChange.setCommentCount(comment_count);
                copChange.setPraiseCount(-1);
                BusProvider.getInstance().post(copChange);

                if (onCommentSuccessListener != null) {
                    onCommentSuccessListener.callback(response.toString());
                }
            }
            qdBaseActivity.displayToast(sendCommentEntity.getMeta().getMsg());
        }
        //评论列表
        else if (params instanceof NetConfigs.RequestArticleComments || params instanceof NetConfigs.RequestQuestionnaireComments) {
            CommentsEntity commentsEntity = QDJsonUtil.Json2Object(response.toString(), CommentsEntity.class);
            if (null != commentsEntity &&
                    null != commentsEntity.getResponse() &&
                    null != commentsEntity.getResponse().getComments()) {
                isCommentEnd = !commentsEntity.getResponse().getComments().isHas_more();
                lastCommentTime = commentsEntity.getResponse().getComments().getLast_time();
                commentsAdapter.appendData(commentsEntity.getResponse().getComments().getList());
                onUIRefreshComplete();
            }
        }
        //POST赞
        else if (params instanceof NetConfigs.RequestLikeIt) {
            NetConfigs.RequestLikeIt requestLikeIt = (NetConfigs.RequestLikeIt) params;
            LikeItEntity likeItEntity = QDJsonUtil.Json2Object(response.toString(), LikeItEntity.class);
            if (likeItEntity.getResponse() != null && likeItEntity.getMeta().getStatus() == NetConfigs.HTTP_RESPONSE_200) {
                //save status
//                praiseDAO.save(requestLikeIt.getTypeId(), requestLikeIt.getGenre(), requestLikeIt.getPraise_type());
                //update ui
//                EventCOPChange copChange = new EventCOPChange(mDetailEnum, articleOrPaperId);
                if (requestLikeIt.getPraise_type().equals("comment")) //更改列表
                {
//                    copChange.setCopId(requestLikeIt.getTypeId());
//                    copChange.setCopEnum(QDEnum.COPEnum.COMMENT);
                    if (onPraiseSuccessListener != null) {
                        onPraiseSuccessListener.callback(response.toString());
                    }
//                    if (commentsAdapter != null)
//                        commentsAdapter.updateListViewItemLikeNumber(requestLikeIt.getTypeId(), likeItEntity.getResponse().getPraise_count());
                } else //更改工具条
                {
//                    copChange.setCopId(articleOrPaperId);
//                    copChange.setCopEnum((mDetailEnum == QDEnum.DetailEnum.ARTICLE ? QDEnum.COPEnum.ARTICLE : QDEnum.COPEnum.PAPER));
                }
//                copChange.setPraiseCount(likeItEntity.getResponse().getPraise_count());
//                BusProvider.getInstance().post(copChange);
            } else {
                //toast
                qdBaseActivity.displayToast(likeItEntity.getMeta().getMsg());
            }
        }
    }

    @Override
    public void onResponseError(NetUtil.NetParams params, Object response) {
        isLoading = false;
        if (params instanceof NetConfigs.RequestArticleComments || params instanceof NetConfigs.RequestQuestionnaireComments) {
            onUIRefreshComplete();
        }
    }

    @Override
    public void onResponseCache(NetUtil.NetParams params, JsonData response) {

    }

    private void showCommentActionDialog(final int commentID, final String content) {
        alertDialog.setItems(onClickItems, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0: {
                        requestPraise(commentID);
                    }
                    break;
                    case 1: {
                        inputBar.requestFocus(commentID);
                    }
                    break;
                    case 2: {
                        ClipboardManager clipboard = (ClipboardManager) qdBaseActivity.
                                getSystemService(Context.CLIPBOARD_SERVICE);
                        ClipData clip = ClipData.newPlainText("simple text", content);
                        clipboard.setPrimaryClip(clip);
                        qdBaseActivity.displayToast(R.string.copy_succesed);
                    }
                    break;
                }
                dialog.dismiss();
            }
        });
        alertDialog.show();
    }

    //点击父评论的赞按钮。
    @Override
    public void onParentLikedClick(int commentParentId) {
        requestPraise(commentParentId);
    }

    //点父评论的的回复按钮。
    @Override
    public void onParentCommentClick(int commentParentId) {
        inputBarRequestFocus(commentParentId);
    }

    private void inputBarRequestFocus(int commentParentId) {
        if (!UserInformationManager.getInstance().isLogin()) {
            Intent intent = new Intent();
            intent.setClass(qdBaseActivity, LoginActivity.class);
            qdBaseActivity.startActivity(intent);
        } else {
            inputBar.requestFocus(commentParentId);
        }
    }

    //外面启动load，顺便把监听的Scorllview拿过来，以后自己监听
    public void loadData(QDCommentView commentView) {
        if (commentView != null && (this.mCommentView == null || commentView != mCommentView)) {
            if (mCommentView != null) {
                mCommentView.setOnRefreshAndLoadMoreListener(null);
            }
            this.mCommentView = commentView;
            this.mCommentView.setOnRefreshAndLoadMoreListener(this);
        }
        if (isCommentEnd)
            return;

        if (isLoading)
            return;
        isLoading = true;
        if (lastCommentTime == 0)
            lastCommentTime = System.currentTimeMillis();
        if (mDetailEnum == QDEnum.DetailEnum.ARTICLE) {
            qdailyNetwork.requestArticleComments(articleOrPaperId, lastCommentTime);
        } else if (mDetailEnum == QDEnum.DetailEnum.VOTE) {
            qdailyNetwork.requestQuestionnaireComments(articleOrPaperId, lastCommentTime);
        } else if (mDetailEnum == QDEnum.DetailEnum.VOTERESULT) {
            qdailyNetwork.requestQuestionnaireComments(articleOrPaperId, lastCommentTime);
        }
    }

    public boolean isCommentEnd() {
        return isCommentEnd;
    }

    public void setIsCommentEnd(boolean isCommentEnd) {
        this.isCommentEnd = isCommentEnd;
    }

    @Override
    public void onRefreshBegin() {

    }

    @Override
    public void onLoadMore() {
        loadData(null);
    }

    @Override
    public void onUIRefreshComplete() {
        QLog.w("CommentController", "isCommentEnd:" + isCommentEnd);
        mCommentView.hasMoreLoadData(!isCommentEnd);
    }

    @Override
    public void inputBarOnClickBtn(InputBar.EInputBarBtnType type) {
        if (type == InputBar.EInputBarBtnType.share) {
            shareDialog.show();
        } else if (type == InputBar.EInputBarBtnType.praise) {
            requestPraise(-1);
        } else if (type == InputBar.EInputBarBtnType.comment) {
            inputBarRequestFocus(-1);
        }
    }

    @Override
    public void inputBarOnClickSendBtn(String content, int parentCommentId) {
        requestComment(parentCommentId, content);
    }

    public interface OnCommentSuccessListener {
        void callback(String data); //服务器返回的，用于卡片和JS交互
    }

    public interface OnPraiseSuccessListener {
        void callback(String data);//服务器返回的，用于卡片和JS交互
    }
}
